﻿using HolterDatabase.Model;
using HolterDatabase.ViewModel;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Ribbon;
using System.Windows.Input;

namespace HolterDatabase
{
    /// <summary>
    /// Logique d'interaction pour MainWindow.xaml
    /// </summary>
    public partial class MainWindow : RibbonWindow
    {
        public MainWindow()
        {
            mainViewModel = new MainWindowViewModel();
            DataContext = mainViewModel;

            InitializeComponent();
        }

        private MainWindowViewModel mainViewModel;

        private void OnAddHolterEntry(object sender, System.Windows.RoutedEventArgs e)
        {
            var activeViewModel = (DataContext as MainWindowViewModel).ActiveViewModel;
            var updateActiveViewModel = true;
            if (activeViewModel != null && activeViewModel.IsDirty)
            {
                updateActiveViewModel = AskForSave();
            }
            if (updateActiveViewModel)
            {
                createNewHolter = true;
                patientCardButton.IsChecked = true;
                (DataContext as MainWindowViewModel).ActiveViewModel = new HolterEntryViewModel(new HolterEntry()) { Mode = HolterEntryViewModelMode.Creation };
                createNewHolter = false;
            }
        }

        private void OnPatientListChecked(object sender, System.Windows.RoutedEventArgs e)
        {
            var activeViewModel = (DataContext as MainWindowViewModel).ActiveViewModel;
            var updateActiveViewModel = true;
            if (activeViewModel != null && activeViewModel.IsDirty)
            {
                updateActiveViewModel = AskForSave();
            }
            if (updateActiveViewModel)
            {
                (DataContext as MainWindowViewModel).ActiveViewModel = new PatientSetViewModel(new PatientSet());
            }
            else
            {
                (sender as RibbonRadioButton).IsChecked = false;
            }
        }

        private void OnHolterListChecked(object sender, System.Windows.RoutedEventArgs e)
        {
            var activeViewModel = (DataContext as MainWindowViewModel).ActiveViewModel;
            var updateActiveViewModel = true;
            if (activeViewModel != null && activeViewModel.IsDirty)
            {
                updateActiveViewModel = AskForSave();
            }
            if (updateActiveViewModel)
            {
                (DataContext as MainWindowViewModel).ActiveViewModel = new HolterSetViewModel(new HolterSet());
            }
            else
            {
                (sender as RibbonRadioButton).IsChecked = false;
            }
        }

        private void OnPatientCardChecked(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!createNewHolter)
            {
                var activeViewModel = (DataContext as MainWindowViewModel).ActiveViewModel;
                var updateActiveViewModel = true;
                if (activeViewModel != null && activeViewModel.IsDirty)
                {
                    updateActiveViewModel = AskForSave();
                }
                if (updateActiveViewModel)
                {
                    (DataContext as MainWindowViewModel).ActiveViewModel = new HolterEntryViewModel(new HolterEntry(selectedRow)) { Mode = HolterEntryViewModelMode.Modification };
                }
                else
                {
                    (sender as RibbonRadioButton).IsChecked = false;
                }
            }
        }

        private bool AskForSave()
        {
            var result = true;
            var messageBoxResult = MessageBox.Show(
                "Il existes des modifications non sauvegardées sur la page courante. Souhaitez vous les sauvegarder maintenant ? Si vous choisissez de ne pas les sauvegarder, elle seront perdues.",
                "Sauvegarder les données ?", 
                MessageBoxButton.YesNoCancel);
            if (messageBoxResult == MessageBoxResult.Yes)
            {
                Save();
            }
            else if (messageBoxResult == MessageBoxResult.Cancel)
            {
                result = false;
            }
            return result;
        }

        private void OnSave(object sender, System.Windows.RoutedEventArgs e)
        {
            Save();
        }

        private void Save()
        {
            var activeViewModel = (DataContext as MainWindowViewModel).ActiveViewModel as DataBaseSetViewModel;
            if (activeViewModel != null)
            {
                activeViewModel.UpdateTable();
            }
            else
            {
                var holterEntryViewModel = (DataContext as MainWindowViewModel).ActiveViewModel as HolterEntryViewModel;
                if (holterEntryViewModel != null)
                {
                    holterEntryViewModel.Save();
                }
            }
        }

        private void OnValidateSearch(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                FindText();
            }
        }

        private void OnSearch(object sender, System.Windows.RoutedEventArgs e)
        {
            FindText();
        }

        private void FindText()
        {
            var dataGrid = content.SafeFindDescendant<DataGrid>();
            if (dataGrid != null)
            {
                var loweredSearchText = searchText.Text.ToLower();
                foreach (var item in dataGrid.Items)
                {
                    var dataRowView = item as System.Data.DataRowView;
                    if (dataRowView != null)
                    {
                        var firstName = (dataRowView.Row["FirstName"] is System.DBNull ? "" : (string)(dataRowView.Row["FirstName"])).ToLower();
                        var lastName = (dataRowView.Row["LastName"] is System.DBNull ? "" : (string)(dataRowView.Row["LastName"])).ToLower();
                        if (firstName.Contains(loweredSearchText) || lastName.Contains(loweredSearchText))
                        {
                            dataGrid.Focus();
                            dataGrid.SelectedItem = dataRowView;
                            dataGrid.ScrollIntoView(dataRowView);
                            break;
                        }
                    }
                }
            }
        }

        private void OnExport(object sender, System.Windows.RoutedEventArgs e)
        {
            var activeViewModel = (DataContext as MainWindowViewModel).ActiveViewModel as DataBaseSetViewModel;
            if (activeViewModel != null)
            {
                activeViewModel.Export();
            }
        }

        private void OnImport(object sender, System.Windows.RoutedEventArgs e)
        {
            var activeViewModel = (DataContext as MainWindowViewModel).ActiveViewModel as DataBaseSetViewModel;
            if (activeViewModel != null)
            {
                activeViewModel.Import();

                if (activeViewModel is PatientSetViewModel)
                {
                    (DataContext as MainWindowViewModel).ActiveViewModel = new PatientSetViewModel(new PatientSet());
                }
                else
                {
                    (DataContext as MainWindowViewModel).ActiveViewModel = new HolterSetViewModel(new HolterSet());
                }
            }
        }

        private void OnHolterListSelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 1 && e.AddedItems[0].ToString() != "{NewItemPlaceholder}")
            {
                exportPdfButton.IsEnabled = true;
                patientCardButton.IsEnabled = true;
                var newItem = e.AddedItems[0] as System.Data.DataRowView;
                if (newItem != null)
                {
                    selectedRow = newItem.Row;
                }
            }
            else
            {
                exportPdfButton.IsEnabled = false;
                patientCardButton.IsEnabled = false;
                selectedRow = null;
            }
        }

        private void OnExportPdfChecked(object sender, System.Windows.RoutedEventArgs e)
        {
            FileStream fs = new FileStream("FichePatient.pdf", FileMode.Create, FileAccess.Write, FileShare.None);
            Document doc = new Document(PageSize.A4, 36, 36, 40, 0);
            PdfWriter writer = PdfWriter.GetInstance(doc, fs);
            doc.Open();
            doc.Add(new Paragraph("CLINIQUE DES CHARMILLES") { Alignment = Element.ALIGN_CENTER });
            doc.Add(new Paragraph("12, Bd P. Brossolette") { Alignment = Element.ALIGN_CENTER });
            doc.Add(new Paragraph("91290 Arpajon - 01.69.26.88.88") { Alignment = Element.ALIGN_CENTER });
            doc.Add(new Paragraph("------------------------") { Alignment = Element.ALIGN_CENTER });
            doc.Add(new Paragraph("Centre d'Etude des Troubles du Rythme") { Alignment = Element.ALIGN_CENTER });
            doc.Add(new Paragraph("Implantation et Surveillance des pacemakers") { Alignment = Element.ALIGN_CENTER });
            doc.Add(new Paragraph("DR F. TOUIL - 01.69.26.88.36") { Alignment = Element.ALIGN_CENTER });

            var examenHolterCHunk = new Chunk("EXAMEN HOLTER");
            examenHolterCHunk.SetUnderline(0.1f, -2f);
            var examenHolterParagraph = new Paragraph(examenHolterCHunk) { Alignment = Element.ALIGN_CENTER };
            examenHolterParagraph.SetLeading(30, 0);
            doc.Add(examenHolterParagraph);

            var nomParagraph = new Paragraph("NOM : " + selectedRow["LastName"]) { Alignment = Element.ALIGN_LEFT };
            nomParagraph.SetLeading(30, 0);
            doc.Add(nomParagraph);

            doc.Add(new Paragraph("PRENOM : " + selectedRow["FirstName"]) { Alignment = Element.ALIGN_LEFT });
            var birthDate = (selectedRow["BirthDate"] is System.DBNull) ? new System.DateTime() : (System.DateTime)(selectedRow["BirthDate"]);
            doc.Add(new Paragraph("DATE DE NAISSANCE : " + birthDate.Day + "." + birthDate.Month + "." + birthDate.Year) { Alignment = Element.ALIGN_LEFT });
            doc.Add(new Paragraph("ADRESSE : " + ((selectedRow["Adress"] is System.DBNull) ? "" : (selectedRow["Adress"] as string).Replace("\r\n", " "))) { Alignment = Element.ALIGN_LEFT });
            doc.Add(new Paragraph("TELEPHONE : " + selectedRow["Phone"]) { Alignment = Element.ALIGN_LEFT });

            var outDate = (selectedRow["OutDate"] is System.DBNull) ? new System.DateTime() : (System.DateTime)(selectedRow["OutDate"]);

            var outTime = (selectedRow["OutTime"] is System.DBNull) ? new System.TimeSpan() : (System.TimeSpan)(selectedRow["OutTime"]);
            doc.Add(new Paragraph("DATE ET HEURE DE POSE : " + outDate.Day + "." + outDate.Month + "." + outDate.Year + " à " + outTime.Hours + "h" + (outTime.Minutes < 10 ? "0" : "") + outTime.Minutes) { Alignment = Element.ALIGN_LEFT });
            doc.Add(new Paragraph("INDICATION : " + selectedRow["Indication"]) { Alignment = Element.ALIGN_LEFT });
            doc.Add(new Paragraph("TRAITEMENT : " + selectedRow["Treatment"]) { Alignment = Element.ALIGN_LEFT });
            doc.Add(new Paragraph("CORRESPONDANT : " + selectedRow["Doctor"]) { Alignment = Element.ALIGN_LEFT });

            PdfContentByte cb = writer.DirectContent;
            cb.SetLineWidth(1.0f);   // Make a bit thicker than 1.0 default
            cb.SetGrayStroke(0.0F); // 1 = black, 0 = white
            cb.MoveTo(36, 440);
            cb.LineTo(550,440);
            cb.Stroke();

            var descActiParagraph = new Paragraph("DESCRIPTIF DE VOTRE ACTIVITE") { Alignment = Element.ALIGN_CENTER };
            descActiParagraph.SetLeading(70, 0);
            doc.Add(descActiParagraph);

            doc.Add(new Paragraph("PENDANT LES 24H") { Alignment = Element.ALIGN_CENTER });

            PdfPTable table = new PdfPTable(3);
            table.TotalWidth = 480f;
            table.LockedWidth = true;
            table.SpacingBefore = 30f;

            table.AddCell(new PdfPCell(new Paragraph("HEURES")) { HorizontalAlignment = 1});
            table.AddCell(new PdfPCell(new Paragraph("EFFORTS")) { HorizontalAlignment = 1 });
            table.AddCell(new PdfPCell(new Paragraph("DOULEURS OU SENSATIONS")) { HorizontalAlignment = 1 });
            table.AddCell("Exempe : 8h00");table.AddCell("Montée des escaliers");table.AddCell("Palpitations");
            table.AddCell(" ");table.AddCell(" ");table.AddCell(" ");
            table.AddCell(" "); table.AddCell(" "); table.AddCell(" ");
            table.AddCell(" "); table.AddCell(" "); table.AddCell(" ");
            table.AddCell(" "); table.AddCell(" "); table.AddCell(" ");
            table.AddCell(" "); table.AddCell(" "); table.AddCell(" ");
            table.AddCell(" "); table.AddCell(" "); table.AddCell(" ");
            table.AddCell(" "); table.AddCell(" "); table.AddCell(" ");
            table.AddCell(" "); table.AddCell(" "); table.AddCell(" ");
            table.AddCell(" "); table.AddCell(" "); table.AddCell(" ");
            table.AddCell(" "); table.AddCell(" "); table.AddCell(" ");
            table.AddCell(" "); table.AddCell(" "); table.AddCell(" ");
            table.AddCell(" "); table.AddCell(" "); table.AddCell(" ");
            table.AddCell(" "); table.AddCell(" "); table.AddCell(" ");
            table.AddCell(" "); table.AddCell(" "); table.AddCell(" ");
            doc.Add(table);

            var lastParagraph = new Paragraph("APPAREIL A RAPPORTER IMPERATIVEMENT LE                         A  ") { Alignment = Element.ALIGN_LEFT };
            lastParagraph.SetLeading(40, 0);
            doc.Add(lastParagraph);

            doc.Close();

            var process = new Process();
            process.StartInfo = new ProcessStartInfo()
            {
                UseShellExecute = true,
                FileName = "FichePatient.pdf"
            };

            process.Start();
            process.WaitForExit();
        }

        private void OnRibbonMouseDown(object sender, MouseButtonEventArgs e)
        {
            ribbon.Focus();
        }

        private bool createNewHolter;
        private System.Data.DataRow selectedRow;
    }
}
